﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace NetFrameworkExtensions.Utils
{
  public class TextFilter
  {
    public TextFilter()
    {
      TermPattern = @"[\d\w]+";
    }

    private string _filter;
    private string _termPattern;
    public string Filter
    {
      get { return _filter; }
      set
      {
        if (_filter == value) return;
        _filter = value;
        CreateMatcher();
      }
    }

    public string TermPattern
    {
      get { return _termPattern; }
      set 
      {
        if (_termPattern == value) return;
        var regex = new Regex(value); // throws exception if cannot create a regex with the pattern
        _termPattern = value;
        CreateMatcher();
      }
    }

    private void CreateMatcher()
    {
      if (string.IsNullOrWhiteSpace(_filter))
        matchers = null;
      else
      {
        var matches = Regex.Matches(_filter.ToPlainText(), TermPattern);
        matchers = matches
          .Cast<Match>()
          .Select(m => new Regex(m.Value.ToLower(), RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant))
          .ToArray();
      }
    }

    private Regex[] matchers;

    public bool Accept(string searchItem)
    {
      if (searchItem == null) return false;
      if (matchers == null) return true;
      var result = matchers.All(m => m.IsMatch(searchItem.ToPlainText()));
      return result;
    }
    public bool Accept(IEnumerable<string> searchItems)
    {
      if (searchItems == null) return false;
      if (matchers == null) return true;
      var si = searchItems.Where(s => s != null).Select(s => s.ToPlainText()).ToArray();
      var result = matchers.All(m => si.Any(s => m.IsMatch(s)));
      return result;
    }
    public bool Accept(params string[] searchItems)
    {
      return Accept((IEnumerable<string>)searchItems);
    }
  }
}
